package com.gcloud.mesh.monitor.timer;

import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.gcloud.mesh.asset.service.IAssetService;
import com.gcloud.mesh.header.enums.MonitorMeter;
import com.gcloud.mesh.header.msg.asset.ListDatacenterMsg;
import com.gcloud.mesh.header.msg.asset.ListDeviceMsg;
import com.gcloud.mesh.header.vo.asset.DatacenterItemVo;
import com.gcloud.mesh.header.vo.asset.DeviceItemVo;
import com.gcloud.mesh.monitor.dao.StatisticsDao;
import com.gcloud.mesh.monitor.entity.StatisticsEntity;

@Component
public class DatacenterTimer {

	@Autowired
	private IAssetService assetService;

	@Autowired
	private StatisticsDao statisticsDao;

	@Scheduled(fixedDelay = 1000 * 60 * 5)
	public void work() {
		for (MonitorMeter meter : MonitorMeter.values()) {
			if (meter.getMeter().contains("air")) {
				setData(1, meter.getMeter(), false);
			} else if (meter.getMeter().contains("ups")) {
				setData(2, meter.getMeter(), false);
			} else if (meter.getMeter().contains("distribution_box")) {
				setData(8, meter.getMeter(), false);
			} else if (meter.getMeter().equals("datacenter.load")){
				setData(8, "environment.distribution_box_power", true);
			}
		}
	}

	private void setData(int type, String meter, boolean tag) {
		List<DatacenterItemVo> items = assetService.listDatacenter(new ListDatacenterMsg());
		for (DatacenterItemVo item : items) {
			ListDeviceMsg msg = new ListDeviceMsg();
			msg.setDatacenterId(item.getId());
			msg.setType(type);
			List<DeviceItemVo> devices = assetService.listDevice(msg);
			double sum = 0;
			for (DeviceItemVo device : devices) {
				StatisticsEntity value = statisticsDao.getLastData(meter, device.getId());
				sum = sum + value.getValue();
			}
			if (sum != 0 && devices.size() > 0) {
				StatisticsEntity entity = new StatisticsEntity();
				entity.setId(UUID.randomUUID().toString());
				entity.setMeter(meter);
				entity.setResourceId(item.getId());
				entity.setTimestamp(new Date());
				if(tag){
					entity.setValue(sum);
				}else{
					entity.setValue(sum / devices.size());
				}
				statisticsDao.save(entity);
			}
		}
	}
}
